import struct
import sys
import traceback

from pathlib import Path


# 转换工具
# 将old.bin 文件转换为 new.bin, 文件长度是 32768 多余部分裁剪，缺少部分用0xff补齐
# python covert.py old.bin new.bin 32768

def doCovert():
    for arg in range(1, len(sys.argv)):
        print(sys.argv[arg])

    old_file_name = sys.argv[1]
    new_file_name = sys.argv[2]
    new_file_length = sys.argv[3]

    new_length = 0

    if not new_file_length.isnumeric():
        print("参数不是数字:{}".format(new_file_length))
    else:
        new_length = int(new_file_length)

    old_file_path = Path(old_file_name)

    if old_file_path.exists() and old_file_path.is_file():
        filelength = old_file_path.stat().st_size

        print("文件【{}】长度:{}".format(old_file_name,filelength))
        print("长度:{}".format(new_length))

        with open("./"+new_file_name,'wb') as fo:
            with open("./"+old_file_name,'rb') as fi:
                if filelength >= new_length:
                    print("截取文件")
                    fo.write(fi.read(new_length))
                    fo.flush()
                else:
                    print("需要补齐")
                    fo.write(fi.read(new_length))
                    for i in range(new_length-filelength):
                        fo.write(struct.pack('B', 0xff))
                    fo.flush()

    else:
        print("读取文件失败，目标不是文件或文件不存在")

if __name__ == '__main__':
    try:
        if len(sys.argv) == 4:
            doCovert()
        else:
            print("参数长度(3个) 当前传入参数:{}个".format(len(sys.argv)-1))
            print("请使用 covert 原文件 新文件 容量 的参数转换长度")
            print("covert old.bin new.bin 32768")

    except Exception as err:
        print("--------------Exception------------")
        print(err)
        traceback.print_exc()
        print("--------------Exception------------")
